import axios from 'axios'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { blobValidate } from '@/utils/zone'
import Conf from '@/utils/conf'

const baseURL = Conf.BASE_API_URL;

export default {
  async name(name, isDelete = true) {
    const url = baseURL + "/common/download?fileName=" + encodeURIComponent(name) + "&delete=" + isDelete;
    try {
      const res = await axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        withCredentials: false,
        headers: { 'Authorization': 'Bearer ' + getToken() }
      });
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data]);
        this.saveAs(blob, decodeURIComponent(res.headers['download-filename']));
      } else {
        await this.printErrMsg(res.data);
      }
    } catch (error) {
      // 处理错误
    }
  },

  async resource(resource) {
    const url = baseURL + "/common/download/resource?resource=" + encodeURIComponent(resource);
    try {
      const res = await axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        withCredentials: false,
        headers: { 'Authorization': 'Bearer ' + getToken() }
      });
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data]);
        this.saveAs(blob, decodeURIComponent(res.headers['download-filename']));
      } else {
        await this.printErrMsg(res.data);
      }
    } catch (error) {
      // 处理错误
    }
  },

  async zip(url, name) {
    const newUrl = baseURL + url;
    try {
      const res = await axios({
        method: 'get',
        url: newUrl,
        responseType: 'blob',
        withCredentials: false,
        headers: { 'Authorization': 'Bearer ' + getToken() }
      });
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data], { type: 'application/zip' });
        this.saveAs(blob, name);
      } else {
        await this.printErrMsg(res.data);
      }
    } catch (error) {
      // 处理错误
    }
  },

  saveAs(text, name, opts) {
    saveAs(text, name, opts);
  },

  async printErrMsg(data) {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
    ElMessage.error(errMsg);
  }
}

